package cn.iocoder.yudao.module.system.controller.admin.exam;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.exam.vo.*;
import cn.iocoder.yudao.module.system.service.exam.ExamDataService;
import cn.iocoder.yudao.module.system.service.exam.ExamTestService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 管理后台 - 测评系统
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - 测评系统")
@RestController
@RequestMapping("/system/exam-test")
@Validated
@Slf4j
public class ExamEvaluationController {

    @Resource
    private ExamTestService examTestService;

    @Resource
    private ExamDataService examDataService;

    @GetMapping("/questions")
    @Operation(summary = "获取测评题列表")
    @PermitAll
    public CommonResult<List<ExamTestQuestionVO>> getTestQuestions(
            @Parameter(description = "测评类型标记值", required = false) @RequestParam(value = "tbl", required = false) String tbl) {

        log.info("获取测评题列表，tbl: {}", tbl);
        List<ExamTestQuestionVO> questions = examTestService.getTestQuestions(tbl);
        return success(questions);
    }

    @GetMapping("/info")
    @Operation(summary = "获取测评相关信息")
    @PermitAll
    public CommonResult<ExamTestInfoVO> getTestInfo(
            @Parameter(description = "测评类型标记值", required = false) @RequestParam(value = "tbl", required = false) String tbl) {

        log.info("获取测评相关信息，tbl: {}", tbl);
        ExamTestInfoVO testInfo = examTestService.getTestInfo(tbl);
        return success(testInfo);
    }

    @GetMapping("/report")
    @Operation(summary = "获取测评结果报告")
    @PermitAll
    public CommonResult<ExamTestReportVO> getTestReport(
            @Parameter(description = "测评类型标记值", required = false) @RequestParam(value = "tbl", required = false) String tbl,
            @Parameter(description = "报告类型，默认3。1：基础版报告；2：专业版报告；3：完整版报告", required = false) @RequestParam(value = "reportType", required = false, defaultValue = "3") String reportType,
            @Parameter(description = "答案，格式：题目detailsId-题目答案选项索引值,题目detailsId2-题目答案选项索引值2,...", required = true) @RequestParam(value = "answer") String answer,
            @Parameter(description = "是否提交所有题目的答案，默认0。0：否，1：是", required = false) @RequestParam(value = "isAllAnswer", required = false) String isAllAnswer) {

        log.info("获取测评结果报告，tbl: {}, reportType: {}, answer: {}, isAllAnswer: {}",
                tbl, reportType, answer, isAllAnswer);
        ExamTestReportVO report = examTestService.getTestReport(tbl, reportType, answer, isAllAnswer);
        return success(report);
    }

    @PostMapping("/submit")
    @Operation(summary = "提交答案并获取报告")
    @PermitAll
    public CommonResult<ExamTestReportVO> submitAnswers(@Valid @RequestBody ExamAnswerSubmitReqVO submitReqVO) {
        log.info("提交测评答案，答案数量: {}",
                submitReqVO.getAnswers() != null ? submitReqVO.getAnswers().size() : 0);
        ExamTestReportVO report = examTestService.submitAnswers(submitReqVO);
        return success(report);
    }

    // ========== 数据库相关接口 ==========

    @GetMapping("/my-reports")
    @Operation(summary = "获取我的测评历史")
    @PermitAll
    public CommonResult<List<ExamTestReportVO>> getMyTestReports() {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        if (userId == null) {
            return success(new ArrayList<>());
        }

        List<ExamTestReportVO> reports = examDataService.getUserTestHistory(userId);
        log.info("获取用户测评历史，userId: {}, 报告数量: {}", userId, reports.size());
        return success(reports);
    }

    @GetMapping("/my-latest-report")
    @Operation(summary = "获取我的最新测评报告")
    @PermitAll
    public CommonResult<ExamTestReportVO> getMyLatestTestReport() {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        if (userId == null) {
            return success(null);
        }

        ExamTestReportVO report = examDataService.getLatestTestReport(userId);
        log.info("获取用户最新测评报告，userId: {}", userId);
        return success(report);
    }

    @GetMapping("/cached-questions")
    @Operation(summary = "获取缓存的测评题列表")
    @PermitAll
    public CommonResult<List<ExamTestQuestionVO>> getCachedTestQuestions(
            @Parameter(description = "测评类型标记值", required = false) @RequestParam(value = "tbl", required = false) String tbl) {

        log.info("获取缓存的测评题列表，tbl: {}", tbl);
        List<ExamTestQuestionVO> questions = examDataService.getQuestions(tbl);
        return success(questions);
    }

    @GetMapping("/cached-info")
    @Operation(summary = "获取缓存的测评信息")
    @PermitAll
    public CommonResult<ExamTestInfoVO> getCachedTestInfo(
            @Parameter(description = "测评类型标记值", required = false) @RequestParam(value = "tbl", required = false) String tbl) {

        log.info("获取缓存的测评信息，tbl: {}", tbl);
        ExamTestInfoVO testInfo = examDataService.getTestInfo(tbl);
        return success(testInfo);
    }

    @DeleteMapping("/clean-cache")
    @Operation(summary = "清理测评缓存数据")
    @PermitAll
    public CommonResult<Boolean> cleanTestCache(
            @Parameter(description = "测评类型标记值", required = false) @RequestParam(value = "tbl", required = false) String tbl) {

        log.info("清理测评缓存数据，tbl: {}", tbl);
        examDataService.cleanExpiredData(tbl);
        return success(true);
    }

    @DeleteMapping("/my-test-record")
    @Operation(summary = "删除我的测评记录")
    @PermitAll
    public CommonResult<Boolean> deleteMyTestRecord(
            @Parameter(description = "测试批次号", required = true) @RequestParam(value = "testBatchNo") String testBatchNo) {

        Long userId = SecurityFrameworkUtils.getLoginUserId();
        if (userId == null) {
            return success(false);
        }

        log.info("删除用户测评记录，userId: {}, testBatchNo: {}", userId, testBatchNo);
        examDataService.deleteUserTestRecord(userId, testBatchNo);
        return success(true);
    }

}
